package com.biostime.qdingding.modules.job;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.job.service.AutoClearService;

/**
 * 自动结算处理类
 * @author phil
 * @version 2015-11-22
 */
@Service
@Lazy(false)
public class AutoClearJob {
	
	@Autowired
	private AutoClearService autoClearService;
	
	protected Logger logger = LoggerFactory.getLogger("autoclear"); //日志对象
	
	private static boolean alive = true; //当前任务是否执行完毕
	private static int CourseCount = 10; //每次读取课程订单数量
	
	private static int Timeout = 1000*60*60; //任务超时时间(一个小时)
	
	/**
	 * 每天晚上10:10自动扣费
	 */
	@Scheduled(cron = "0 10 22 * * ?")  
	public void schedule(){
		
		alive = true;
		Date startOn = new Date();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(Timeout);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				alive = false;
				logger.info(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss") + " 自动结算--任务超时");
			}
		}).start();
		
		logger.info(DateUtils.formatDate(startOn, "yyyy-MM-dd HH:mm:ss") + (" 自动结算--开始"));
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		
		while(alive){
			synchronized (AutoClearJob.class) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						synchronized (AutoClearJob.class) {
							//1、从数据库中取所有预定状态的课程订单进行扣费
							List<HashMap<String,Object>> courses = autoClearService.getOrderdCourse(CourseCount, calendar.getTime());
							
							if(courses != null && courses.size()>0){
								
								for(HashMap<String,Object> map : courses){
									int type = -1;
									if(map.containsKey("type")){
										type = StringUtils.toInteger(map.get("type"));
									}
									
									int courseId = -1;
									if(map.containsKey("courseId")){
										courseId = StringUtils.toInteger(map.get("courseId"));
									}
									
									//2、对单节课进行扣费[0-普通课程，1-户外课程]
									autoClearService.autoClearIn(type, courseId);
									
									/** 课程类型不参与扣费，只用在优惠券功能（20160316）
									//2、对单节课进行扣费[0-普通课程，1-户外课程]
									switch(type){
										case 0:
											autoClearService.autoClearIn(type, courseId);
											break;
										/*case 1: //暂时无户外课程
											autoClearService.autoClearOut(type, courseId);
											break;
										default:
											break;
									}**/
								}
							}else{
								//3、如果不存在需要扣费的订单
								AutoClearJob.alive = false;
							}
							
							AutoClearJob.class.notify();
						}
					}
				}).start();
				
				try {
					AutoClearJob.class.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		Date endOn = new Date();
		long time = (endOn.getTime() - startOn.getTime());
		logger.info(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss") + (" 自动结算--结束") + " 耗时：" + time + " ms");
	}
}
